package com.example.dao.impl;

import com.example.dao.UserDao;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: wyp
 * @Date: 2021/9/2 13:54
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean add(User user) {
        Object[] args = {user.getId(),user.getName(),user.getAddr()};
        int result = jdbcTemplate.update("insert into user(id,name,addr) values (?,?,?)",args);
        return result > 0;
    }

    @Override
    public boolean update(User user) {
        Object[] args = {user.getName(),user.getAddr(),user.getId()};
        int result = jdbcTemplate.update("update user set name = ?,addr = ? where id = ?",args);
        return result > 0;
    }

    @Override
    public boolean remove(User user) {
        Object[] args = {user.getId()};
        int result = jdbcTemplate.update("delete from user where id = ?",args);
        return result > 0;
    }

    @Override
    public int selectCount() {
        return jdbcTemplate.queryForObject("select count(*) from user", Integer.class);
    }

    @Override
    public User selectUser(Integer id) {
        return jdbcTemplate.queryForObject("select * from user where id = ?",
                new BeanPropertyRowMapper<User>(User.class),
                id);
    }

    @Override
    public List<User> selectList() {
        return jdbcTemplate.query("select * from user",
                new BeanPropertyRowMapper<User>(User.class));
    }

    @Override
    public int batchAdd(List<Object[]> userList) {
        int[] batchUpdate = jdbcTemplate.batchUpdate("insert into user value(?,?,?)", userList);
        return batchUpdate.length;
    }

    @Override
    public int batchUpdate(List<Object[]> userList) {
        int[] batchUpdate = jdbcTemplate.batchUpdate("update user set name = ?,addr = ? where id = ?", userList);
        return batchUpdate.length;
    }

    @Override
    public int batchRemove(List<Object[]> userList) {
        int[] batchUpdate = jdbcTemplate.batchUpdate("delete from user where id = ?", userList);
        return batchUpdate.length;
    }
}
